#include "ble_hid_remote.h"
#include "bt_debug.h"

// HID报告描述符
static const uint8_t hid_report_map[] = {
    0x05, 0x01,  // Usage Page (Generic Desktop)
    0x09, 0x06,  // Usage (Keyboard)
    0xA1, 0x01,  // Collection (Application)
    0x85, 0x01,  //   Report ID (1)
    0x05, 0x07,  //   Usage Page (Key Codes)
    0x19, 0xE0,  //   Usage Minimum (224)
    0x29, 0xE7,  //   Usage Maximum (231)
    0x15, 0x00,  //   Logical Minimum (0)
    0x25, 0x01,  //   Logical Maximum (1)
    0x75, 0x01,  //   Report Size (1)
    0x95, 0x08,  //   Report Count (8)
    0x81, 0x02,  //   Input (Data, Variable, Absolute)
    0x95, 0x01,  //   Report Count (1)
    0x75, 0x08,  //   Report Size (8)
    0x81, 0x01,  //   Input (Constant)
    0x95, 0x06,  //   Report Count (6)
    0x75, 0x08,  //   Report Size (8)
    0x15, 0x00,  //   Logical Minimum (0)
    0x25, 0x65,  //   Logical Maximum (101)
    0x05, 0x07,  //   Usage Page (Key Codes)
    0x19, 0x00,  //   Usage Minimum (0)
    0x29, 0x65,  //   Usage Maximum (101)
    0x81, 0x00,  //   Input (Data, Array)
    0xC0         // End Collection
};

// HID服务UUID
static const bt_uuid_t HID_SERVICE_UUID = {
    .type = BT_UUID_TYPE_16,
    .u.uuid16 = BLE_UUID_HID_SERVICE
};

// 初始化HID服务
bt_status_t ble_hid_init(ble_hid_service_t *p_hid)
{
    bt_status_t status;
    bt_gatt_service_t service;
    
    // 配置HID服务
    service.starting_handle = 0x0050;
    service.ending_handle = 0x0060;
    service.uuid = HID_SERVICE_UUID;
    
    // 注册服务
    status = bt_gatts_service_register(&service, &p_hid->service_handle);
    if (status != BT_STATUS_SUCCESS) {
        return status;
    }
    
    // 配置报告特征值
    bt_gatts_characteristic_t report_char = {
        .uuid = {.type = BT_UUID_TYPE_16, .u.uuid16 = 0x2A4D},
        .properties = BT_GATT_CHAR_PROP_READ | BT_GATT_CHAR_PROP_NOTIFY,
        .permission = BT_GATTS_PERMISSION_READ
    };
    
    // 添加报告特征值
    status = bt_gatts_characteristic_add(p_hid->service_handle,
                                       &report_char,
                                       &p_hid->report_cccd_handle);
    
    return status;
}

// 发送按键报告
bt_status_t ble_hid_keys_send(ble_hid_service_t *p_hid, hid_keys_t *p_keys)
{
    if (!p_hid->is_notification_enabled) {
        return BT_STATUS_FAIL;
    }
    
    bt_gatt_handle_value_notification_t notification;
    notification.handle = p_hid->report_cccd_handle;
    notification.value_len = sizeof(hid_keys_t);
    notification.value = (uint8_t*)p_keys;
    
    return bt_gatts_send_notification(p_hid->connection_handle, &notification);
} 